package com.qdlc.p2p.biz.processor.task;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.processor.event.NoticeValueEvent;
import com.qdlc.p2p.biz.service.impl.NoticeServiceImpl;
import com.qdlc.p2p.biz.sms.SmsProtalProviderChooser;
import com.qdlc.p2p.common.core.queue.TaskProcessorException;
import com.qdlc.p2p.common.core.queue.ValueEvent;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.NoticeTypeHelper;
import com.qdlc.p2p.dal.common.NoticeTypeHelper.NidType;
import com.qdlc.p2p.dal.dao.NoticeDao;
import com.qdlc.p2p.dal.dto.Notice;
import com.qdlc.p2p.dal.dto.NoticeType;

/**
 * 发送短信
 * @see NoticeServiceImpl#sendSms(Notice s)
 * @author linya 2016-01-17
 */
@Service
public class NoticeSmsTaskProcessor extends AbstractTaskProcessor {

	private static Logger logger = Logger.getLogger(NoticeSmsTaskProcessor.class);
	
	@Resource
	NoticeDao noticeDao;
	
	@Override
	public boolean supports(ValueEvent event) {
		return event instanceof NoticeValueEvent;
	}

	@Override
	protected void process0(ValueEvent event) throws TaskProcessorException {
		NoticeValueEvent smsEvent = (NoticeValueEvent) event;
		Notice s = smsEvent.getNotice();
        
		String mobile = s.getReceiveAddr();
        String content = StringUtil.isNull(s.getContent());

        logger.debug("contentString=========" + content);
        logger.debug("mobile=========" + mobile);

        // 如果没有为短信配置特殊的send_route则直接通过默认的短信通道发送
        NoticeType smsType = NoticeTypeHelper.getValue(s.getNid(), NidType.NOTICE_SMS);
        String sendRoute = smsType.getSendRoute();
        SmsProtalProviderChooser.SmsResult smsResult =  SmsProtalProviderChooser.choice(sendRoute).send(mobile, content);
        if(smsResult.isSuccess()){
        	s.setStatus(1);
        }else{
        	s.setStatus(0);
        }
        s.setResult(smsResult.getMessage());
        noticeDao.save(s);		
	}

}
